package com.lw.lost.activity

import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.lw.lost.databinding.ActivityRegisterBinding
import com.lw.lost.db.DBlost

class RegisterActivity : AppCompatActivity() {

    private lateinit var binding: ActivityRegisterBinding
    private lateinit var db: DBlost

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityRegisterBinding.inflate(layoutInflater)
        setContentView(binding.root)

        db = DBlost(this)
        initViews()
    }

    private fun initViews() {
        binding.ivBack.setOnClickListener {
            finish()
        }

        binding.btnRegister.setOnClickListener {
            val username = binding.etUsername.text.toString()
            val password = binding.etPassword.text.toString()
            val name = binding.etName.text.toString()
            val phone = binding.etPhone.text.toString()
            val age = binding.etAge.text.toString()
            val gender = if (binding.rbMale.isChecked) 0 else 1

            // 验证输入
            if (username.isEmpty()) {
                binding.tilUsername.error = "请输入用户名"
                return@setOnClickListener
            }

            if (password.isEmpty()) {
                binding.tilPassword.error = "请输入密码"
                return@setOnClickListener
            }

            if (name.isEmpty()) {
                binding.tilName.error = "请输入姓名"
                return@setOnClickListener
            }

            if (phone.isEmpty()) {
                binding.tilPhone.error = "请输入手机号"
                return@setOnClickListener
            }

            if (age.isEmpty()) {
                binding.tilAge.error = "请输入年龄"
                return@setOnClickListener
            }

            // 插入用户数据
            val userId = db.userDao.insert(
                username = username,
                password = password,
                name = name,
                phone = phone,
                status = 1, // 默认状态为1
                gender = gender,
                age = age.toInt()
            )

            if (userId > 0) {
                Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show()
                finish()
            } else {
                Toast.makeText(this, "注册失败，请重试", Toast.LENGTH_SHORT).show()
            }
        }
    }
} 